﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Hangfire;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace TL_Cloud.API.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
  
    [Route("api/[controller]")] 
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        private readonly IHostingEnvironment _env;
        private readonly ILoggerFactory loggerFactory;
        public FileUploadController(IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            this._env = env;
            this.loggerFactory = loggerFactory;
        }

        [HttpGet]
        public IActionResult Get()
        { 
            return Ok(new string[] { "1111","2s"});
        }        
        /// <summary>
        ///文件上传
        /// </summary>
        /// <param name="webFloder">web文件夹</param>
        /// <returns></returns>
        [HttpPost(Name ="PostFile")]
        public IActionResult PostFile(string webFloder)
        {
            //string webFloder = "";
            try
            {
                long size = 0;
                var files = Request.Form.Files; 
                string localpath = _env.WebRootPath.Replace("\\","/")+ webFloder;
                if (System.IO.Directory.Exists(localpath) == false)
                {
                    System.IO.Directory.CreateDirectory(localpath);
                }
                List<string> lstFileNames = new List<string>();
                foreach (var file in files)
                {
                    size = 0;
                    var filename = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    //这个hostingEnv.WebRootPath就是要存的地址可以改下
                    string webFile = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(filename);
                    filename = System.IO.Path.Combine(localpath, webFile);
                    size += file.Length;
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    lstFileNames.Add(webFile);
                }
                return Ok(lstFileNames.Select(n => new { file = webFloder + n }).ToList());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}